package edu.scut.yi.yx.processer;

import java.sql.SQLException;

import com.electrotank.electroserver5.extensions.api.PluginApi;
import com.electrotank.electroserver5.extensions.api.value.EsObject;
import com.electrotank.electroserver5.extensions.api.value.EsObjectRO;

import edu.scut.yi.yx.dbmanager.DatabaseJDBCPlugin;
import edu.scut.yi.yx.lobbymanager.Command;

public class RemoveBuddyProcesser extends AbstractProcesser{
	
	private DatabaseJDBCPlugin databaseJDBCPlugin;
	private EsObject removeBuddyResponse;

	@Override
	public String getCommand() {
		// TODO Auto-generated method stub
		return Command.RemoveBuddy.getCode();
	}

	@Override
	public void process(String user, EsObjectRO message, PluginApi api) {
		// TODO Auto-generated method stub
		String buddy = message.getString(Command.Message.getCode());
		databaseJDBCPlugin = (DatabaseJDBCPlugin)api.getServerPlugin("DatabaseJDBCPlugin");
		if(!api.isBuddy(user, buddy)){
			removeBuddyResponse = new EsObject();
			removeBuddyResponse.setString(Command.Action.getCode(), Command.RemoveBuddy.getCode());
			removeBuddyResponse.setString(Command.State.getCode(), Command.Failed.getCode());
			removeBuddyResponse.setString(Command.Message.getCode(), Command.NotBuddy.getCode());
		}else{
			api.removeBuddy(user, buddy);
		try{
			boolean result = databaseJDBCPlugin.executeSQL("DELETE FROM buddylist WHERE username = '"+user+"' AND "+"buddy = '"+buddy+"';");
			removeBuddyResponse = new EsObject();
			if(result){
				api.removeBuddy(user, buddy);
				removeBuddyResponse.setString(Command.Action.getCode(), Command.RemoveBuddy.getCode());
				removeBuddyResponse.setString(Command.State.getCode(), Command.Success.getCode());
			}else{
				removeBuddyResponse.setString(Command.Action.getCode(), Command.RemoveBuddy.getCode());
				removeBuddyResponse.setString(Command.State.getCode(), Command.Failed.getCode());
			}
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
			api.sendPluginMessageToUser(user, removeBuddyResponse);
	}

}
